from django.http import HttpResponse, JsonResponse, HttpRequest
from django.middleware.csrf import get_token
from django.shortcuts import render
from django import views, http
from django.urls import reverse
from django.utils import timezone

from Book_exaln_system.models import ExaminationForPeople
from Choose_coach_system.models import ChooseCoach
from login_system.models import User
from .forms import RootForm, adduser
from .models import RootModel
from bs4 import BeautifulSoup


# Create your views here.

def getErrorText(html):
    html = str(html)
    soup = BeautifulSoup(html, 'lxml')
    return soup.text


class Root(views.View):

    def get(self, req):
        return render(req, 'root/login.html', context={'form': RootForm()})

    def post(self, req):
        username = req.POST.get('username')
        password = req.POST.get('password')
        v_c = req.POST.get('verifycode')
        if req.session['verifycode'] != v_c:
            error = 'Verification code error'
        else:
            user = RootModel.objects.filter(username=username).first()
            if not user:
                error = 'No user name'
            else:
                if not user.check_pwd(password):
                    error = 'Incorrect password'
                else:
                    return http.HttpResponseRedirect(reverse('root@index'))
        return render(req, 'root/login.html', context={'form': RootForm(), 'error': error})


def index(req):
    return render(req, 'root/index.html', context={})


def managesys(request):
    t = request.GET.get('type')
    dict_user = {'stud': 'student', 'teach': 'teacher', 'test': 'examination'}
    if t == 'score':
        query = ExaminationForPeople.objects.filter(score=None).all()
        query2 = ExaminationForPeople.objects.exclude(score=None).all().order_by('student__name')
        return render(request, 'root/test_score.html', context={'query': query, 'query2': query2})
    if t == 'test':


        return render(request, 'root/statistics.html', context={'courses': 0, 'exam': 0,
                                                                'sub1': 0,
                                                                'sub2': 0,
                                                                'sub3':0,
                                                                'sub4': 0,
                                                                })
    if t == 'cancel':
        sql = ChooseCoach.objects.filter(time_out=False).all()
        return render(request, 'root/cancel.html', context={'sql': sql})
    return render(request, 'root/sql_manage.html', context={'type': dict_user[t]})


def manageform(request):
    t = request.GET.get('type')
    u_t = request.GET.get('user-type')
    print(t, u_t)
    query = None
    form = None
    if u_t == 'student':
        i_c = '0'
        if t == 'add':
            form = adduser({'identity_c': i_c})
        elif t in ['query', 'amend', 'cancel']:
            query = User.objects.filter(identity_c=i_c).all()

    elif u_t == 'teacher':
        i_c = '1'
        if t == 'add':
            form = adduser(initial={'identity_c': i_c})
        elif t in ['query', 'amend', 'cancel']:
            query = User.objects.filter(identity_c=i_c).all()

    else:
        pass
    csrf_token = get_token(request)
    return render(request, 'root/manage_form.html',
                  context={'form': form, 'type': t, 'user_type': u_t, 'query': query, 'csrf_token': csrf_token})


def adduserView(request):
    if request.method == "POST":
        msg = adduser(request.POST)
        if msg.is_valid():
            msg.save()
            return HttpResponse("<script>alert('Succeeded in creating a user.！');window.history.go(-1)</script>")
        print(msg.errors)
        return HttpResponse("<script>alert('" + getErrorText(msg.errors) + "');window.history.go(-1)</script>")

    else:
        return HttpResponse("<script>alert('The data is wrong');window.history.go(-1)</script>")


def deluser(request):
    if request.method == "POST":
        user = User.objects.filter(username=request.POST.get('username')).first()
        if user:
            user.delete()
            return HttpResponse("successfully delete！")
        else:
            return HttpResponse("The data is wrong")
    else:
        return HttpResponse("The data is wrong")


def amenduser(request):
    if request.method == "GET":
        user = User.objects.filter(username=request.GET.get('username')).first()
        if user:
            form = adduser(instance=user)
            print(user)
            return render(request, 'root/amend_form.html', context={'form': form, 'username': user.username})
        else:
            return HttpResponse("The data is wrong")
    else:

        user = User.objects.filter(username=request.POST.get('old-username')).first()
        if request.POST.get('old-username') != request.POST.get('username') and User.objects.filter(
                username=request.POST.get('username')).filter():
            return HttpResponse(
                "<script>alert('The new user name is already in use. Please change it');window.history.go(-1)</script>")
        # user.username = request.POST.get('username')
        # user.name = request.POST.get('name')
        # user.age = request.POST.get('age')
        # user.tel = request.POST.get('tel')
        # user.driving_license_type = request.POST.get('driving_license_type')
        user.password = request.POST.get('password')
        user.save()
        return HttpResponse("<script>alert('modify successfully');window.history.go(-1)</script>")


def testScore(request):
    try:
        item = ExaminationForPeople.objects.filter(id=request.POST.get('id')).first()
        item.score = request.POST.get('score')
        if (item.exaln.examination_type in (1,3,4)) and float(request.POST.get('score'))>=90:
            item.sbj_pass = True
        if(item.exaln.examination_type == 2) and float(request.POST.get('score'))>=80:
            item.sbj_pass = True
        item.reason_for_failure = request.POST.get('reason_for_failure') if request.POST.get(
            'reason_for_failure') else None
        item.save()
        return HttpResponse('Scoring successful')
    except Exception as e:
        return HttpResponse(e)


def statistics(request):
    print(request.POST)
    if request.POST.get("start") == "" or request.POST.get("end") == "":
        return JsonResponse({"status": '500'})
    t1 = timezone.datetime.strptime(request.POST.get("start"), '%Y-%m-%d')
    t2 = timezone.datetime.strptime(request.POST.get("end"), '%Y-%m-%d')
    if t1 < t2:
        t1, t2 = t2, t1

    courses = 0
    exam = 0
    for i in ChooseCoach.objects.all():
        if t2 < i.train_time <= t1:
            courses += 1
    for i in ExaminationForPeople.objects.all():
        if t2 < i.exaln.examination_time <= t1:
            exam += 1
    subs = [0, 0, 0, 0]
    sub_all = [
        len(ExaminationForPeople.objects.filter(exaln__examination_type=1,exaln__examination_time__gt=t2,
                                                exaln__examination_time__lt=t1).all()),
        len(ExaminationForPeople.objects.filter(exaln__examination_type=2,exaln__examination_time__gt=t2,
                                                exaln__examination_time__lt=t1).all()),
        len(ExaminationForPeople.objects.filter(exaln__examination_type=3,exaln__examination_time__gt=t2,
                                                exaln__examination_time__lt=t1).all()),
        len(ExaminationForPeople.objects.filter(exaln__examination_type=4,exaln__examination_time__gt=t2,
                                                exaln__examination_time__lt=t1).all())
    ]
    for i in range(4):
        for j in ExaminationForPeople.objects.filter(exaln__examination_type=i + 1,exaln__examination_time__gt=t2,
                                                     exaln__examination_time__lt=t1).all():
            if j.sbj_pass:
                subs[i] += 1
    examination = ExaminationForPeople.objects.filter(exaln__examination_time__gt=t2,
                                                      exaln__examination_time__lt=t1).all()
    book_msg = ChooseCoach.objects.filter(train_time__gt=t2, train_time__lt=t1).all()
    print(subs,sub_all)
    return render(request, 'root/statistics.html', {'courses': courses, 'exam': exam,
                                                    'sub1': str("%.2f"%(subs[0] / sub_all[0]*100))+'%' if sub_all[0] != 0 else 0,
                                                    'sub2': str("%.2f"%(subs[1] / sub_all[1]*100))+'%' if sub_all[1] != 0 else 0,
                                                    'sub3': str("%.2f"%(subs[2] / sub_all[2]*100))+'%' if sub_all[2] != 0 else 0,
                                                    'sub4': str("%.2f"%(subs[3] / sub_all[3]*100))+'%' if sub_all[3] != 0 else 0,
                                                    'examination': examination,
                                                    'book_msg': book_msg
                                                    })
